package com.huizu.api.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.huizu.api.domain.Commentary;
import com.huizu.api.domain.Coupon;
import com.huizu.api.domain.GoodType;
import com.huizu.api.domain.Spec1Api;
import com.huizu.api.domain.SpecApi;
import com.huizu.api.mapper.ShopApiMapper;
import com.huizu.api.service.IShopApiService;
import com.huizu.common.core.domain.entity.SysUser;
import com.huizu.common.utils.ShiroUtils;
import com.huizu.framework.shiro.service.SysPasswordService;
import com.huizu.pay.util.PayInterface;
import com.huizu.system.service.ISysUserService;

import org.springframework.transaction.annotation.Transactional;

/**
 * 会员信息Service业务层处理
 *
 * @date 2021-09-14
 */
@Service
public class ShopApiServiceImpl implements IShopApiService {
	@Autowired
	private ShopApiMapper dao;
	@Value("${huizu.url}")
	private String url;

	// 轮播图
	public List<String> getRelation(Map<String, Object> map) {
		map.put("model", 1);
		return dao.getRelation(map);
	}

	// 一级商品类型
	public List<GoodType> getgoodType(Map<String, Object> param) {
		param.put("pid", 0);
		List<GoodType> list = new ArrayList<>();
		GoodType type = new GoodType();
		type.setId(0L);
		type.setCateTitle("推荐");
		type.setPid(0L);
		list.add(type);
		List<GoodType> list1 = dao.getgoodType(param);
		list.addAll(list1);
		return list;
	}

	// 二级商品类型
	public List<GoodType> getTwogoodType(Map<String, Object> param) {
		List<GoodType> list = dao.getgoodType(param);
		return list;
	}

	// 推荐门店
	public List<Map<String, Object>> getShopList(Map<String, Object> param) {
		List<Map<String, Object>> list = dao.getShopList();
		for (Map<String, Object> m : list) {
			param.put("shopId", m.get("shopId"));
			param.put("isRecommend", 1);
			List<Map<String, Object>> list1 = dao.getGoodsByShopId(param);
			m.put("goodsList", list1);
		}
		return list;
	}

	// 门店详情
	public Map<String, Object> getShopDetail(Map<String, Object> map) {
		Map<String, Object> res = dao.getShopDetail(map);
		map.put("shopId", res.get("shopId"));
		map.put("isRecommend", 1);
		List<Map<String, Object>> list1 = dao.getGoodsByShopId(map);
		res.put("goodsList", list1);
		return res;
	}

	// 推荐商品
	public List<Map<String, Object>> getGoodsByShopId(Map<String, Object> param) {
		param.put("isRecommend", 1);
		return dao.getGoodsByShopId(param);
	}

	// 搜索商品列表
	public List<Map<String, Object>> queryGoods(Map<String, Object> param) {

		List<Long> list = dao.getCateList(param);
		for (Long cateId : list) {
			dao.updateGoodsCateNum(cateId);
			param.put("cateId", cateId);
			dao.insertMemberSearchLogs(param);
		}
		return dao.getGoodsByShopId(param);
	}
	
	// 种类商品列表
	public List<Map<String, Object>> queryGoodsByCate(Map<String, Object> param) {
		if(param.containsKey("priceFlag") && !"".equals(String.valueOf(param.containsKey("priceFlag")))){
			param.put("order", String.valueOf(param.get("priceFlag")));
			param.put("sort", "market_price");
		}
		if(param.containsKey("discountsFlag") && !"".equals(String.valueOf(param.containsKey("discountsFlag")))){
			param.put("order1", String.valueOf(param.get("discountsFlag")));
			param.put("sort1", "discounts");
		}
		return dao.getGoodsByShopId(param);
	}
	
	

	// 搜索排行及历史
	public Map<String, Object> getSearchHis(Map<String, Object> param) {
		Map<String, Object> map = new HashMap<>();
		map.put("memberHis", dao.getMemberCateLogs(param));
		map.put("putHis", dao.getMemberCatePut(param));
		map.put("cateHis", dao.getCateFrist());
		return map;
	}

	// 商品详情
	public Map<String, Object> getGoodsDetail(Map<String, Object> map) {
		Map<String, Object> res = dao.getGoodsDetail(map);
		res.put("imageList", dao.getGoodsImage(map));
		List<Commentary> list = dao.getStoreGoodsCommentary(map);
		for (Commentary cm : list) {
			List<String> list1 = dao.getStoreGoodsCommentaryDetail(cm);
			cm.setImages(list1);
		}
		res.put("commentaryList", list);
		return res;
	}

	// 获取商品规格
	public List<Spec1Api> getSpec(Map<String, Object> param) {
		List<Map<String, Object>> list = dao.getSpec(param);
		Set<Map<String, Object>> set = new HashSet<Map<String, Object>>();
		Set<Map<String, Object>> set1 = new HashSet<Map<String, Object>>();
		for (Map<String, Object> m : list) {
			String[] key = String.valueOf(m.get("key")).split("_");
			String[] keyName = String.valueOf(m.get("keyName")).split(",");
			for (int i = 0; i < key.length; i++) {
				Map<String, Object> m1 = new HashMap<>();
				m1.put("id", key[i]);
				m1.put("name", keyName[i]);
				set.add(m1);
			}
		}
		for (Map<String, Object> m : set) {
			String[] name = String.valueOf(m.get("name")).split(":");
			Map<String, Object> m1 = new HashMap<>();
			m1.put("specName", name[0]);
			m1.put("specId", dao.getSpecId(m));
			set1.add(m1);
		}
		List<Spec1Api> list2 = new ArrayList<Spec1Api>();
		for (Map<String, Object> m : set1) {
			Spec1Api specNew = new Spec1Api();
			List<SpecApi> list3 = new ArrayList<SpecApi>();
			for (Map<String, Object> m1 : set) {
				String[] name = String.valueOf(m1.get("name")).split(":");
				if (name[0].equals(String.valueOf(m.get("specName")))) {
					SpecApi api = new SpecApi();
					api.setId(Integer.parseInt(String.valueOf(m1.get("id"))));
					api.setName(name[1]);
					list3.add(api);
				}
			}
			Collections.sort(list3);
			specNew.setSpecId(Integer.parseInt(String.valueOf(m.get("specId"))));
			specNew.setSpecName(String.valueOf(m.get("specName")));
			specNew.setList(list3);
			list2.add(specNew);
		}
		Collections.sort(list2);
		return list2;
	}

	// 价格查询
	public float getSpecPrice(Map<String, Object> map) {
		return dao.getSpecPrice(map);
	}

	// 购物车操作
	public int insertCart(Map<String, Object> map) {
		String count = dao.getCartCountByGoodsId(map);
		int i = 0;
		if (count == null || "".equals(count)) {
			map.put("id", null);
			dao.insertCart(map);
			i = Integer.parseInt(map.get("id").toString());
		} else {
			i = Integer.parseInt(count);
			dao.updateCart(map);
		}
		return i;
	}

	// 修改购物车数量
	public int updateCartNum(Map<String, Object> map) {
		return dao.updateCartNum(map);
	}

	// 购物车列表
	public List<Map<String, Object>> getCartList(Map<String, Object> map) {
		List<Map<String, Object>> list = dao.getCartShop(map);
		for (Map<String, Object> m : list) {
			map.put("shopId", m.get("shopId"));
			m.put("goodsList", dao.getCartGoods(map));
		}
		return list;
	}

	// 删除购物车
	public void removeCart(Map<String, Object> map) {
		String[] ids = String.valueOf(map.get("ids")).split(",");
		for (int i = 0; i < ids.length; i++) {
			map.put("cartId", ids[i]);
			dao.removeCart(map);
		}
	}

	// 添加地址信息
	public int insertAddress(Map<String, Object> map) {
		return dao.insertAddress(map);
	}

	// 地址列表
	public List<Map<String, Object>> getAddressList(Map<String, Object> map) {
		return dao.getAddressList(map);
	}

	public Map<String, Object> getAddress(Map<String, Object> map) {
		return dao.getAddress(map);
	}

	// 删除地址
	public int deleteAddress(Map<String, Object> map) {
		return dao.deleteAddress(map);
	}

	// 默认地址
	public int updateDefaultFlag(Map<String, Object> map) {
		return dao.updateDefaultFlag(map);
	}

	// 添加订单
	@Transactional
	public Map<String, Object> insertOrder(Map<String, Object> map, HttpServletRequest request) throws Exception {
		Map<String, Object> rem = new HashMap<>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String orderCode = "DD" + sdf.format(new Date()) + String.format("%04d", new Random().nextInt(9999)); // 预下单订单编号
		List<Map<String, Object>> shopIds = dao.getShopIdByCartId(map);
		BigDecimal totalPrice = new BigDecimal("0");
		int i = 1;
		for (Map<String, Object> m : shopIds) {
			m.put("cardIds", map.get("cardIds"));
			BigDecimal totalPrice1 = new BigDecimal("0");
			BigDecimal actualPrice = new BigDecimal("0");
			BigDecimal totalNum = new BigDecimal("0");
			BigDecimal freight=new BigDecimal("0");
			BigDecimal discountPrice=new BigDecimal("0");
			BigDecimal rebatePrice=new BigDecimal("0");
			map.put("shopId", m.get("shopId"));
			List<Map<String, Object>> cardList = dao.getCartGoodsByCartId(map);
			String subOrder = orderCode + i;
			for (Map<String, Object> m1 : cardList) {
				String isFreeShipping=String.valueOf(m1.get("isFreeShipping"));
				BigDecimal freePrice=new BigDecimal(String.valueOf(m1.get("freePrice")));
				BigDecimal marketPrice=new BigDecimal(String.valueOf(m1.get("marketPrice")));
				
				BigDecimal discounts=new BigDecimal(String.valueOf(m1.get("discounts")));
				if("0".equals(isFreeShipping)){
					freight=freight.add(new BigDecimal("freePrice"));
				}
				BigDecimal num = new BigDecimal(String.valueOf(m1.get("totalNum")));
				totalPrice1 = totalPrice1.add(marketPrice.multiply(num));
				totalPrice = totalPrice.add(marketPrice.multiply(num).multiply(discounts)).subtract(freePrice);
				actualPrice=actualPrice.add(marketPrice.multiply(num).multiply(discounts)).subtract(freePrice);
				rebatePrice=rebatePrice.add((marketPrice.subtract(marketPrice.multiply(discounts))).multiply(num));
				totalNum = totalNum.add(num);
				m1.put("subOrder", subOrder);
				dao.insertOrderDetail(m1);
			}
			map.put("orderCode", orderCode);
			map.put("subOrder", subOrder);
			map.put("totalNum", totalNum);
			map.put("totalPrice", totalPrice1);
			map.put("rebatePrice", rebatePrice);
			map.put("freight", freight);
			Coupon  coupon=dao.getOrderCoupon(map);
			if(coupon!=null){
				if(coupon.getUserFlag().longValue()==1){
					discountPrice=discountPrice.add(coupon.getDiscountPrice());
					actualPrice=actualPrice.subtract(coupon.getDiscountPrice());
					totalPrice = totalPrice.subtract(coupon.getDiscountPrice());
					dao.updateOrderCoupon(map);
				}else{
					rem.put("code", 1);
					rem.put("mag", "优惠卷已使用或已过期");
					return rem;
				}
			}else {
				rem.put("code", 1);
				rem.put("mag", "请重新选择优惠卷");
				return rem;
			}
			map.put("actualPrice", actualPrice);
			map.put("discountPrice", discountPrice);
			dao.insertOrder(map);
			i++;
		}
		if (totalPrice.compareTo(new BigDecimal("0")) == 1) {
			map.put("price", 0.01);
		} else {
			map.put("price", totalPrice);
		}
		int payType = Integer.parseInt(String.valueOf(map.get("payType")));
		if (payType == 1) {// 微信
			map.put("url", url + "/shuiweilai/api/WxcallbackUrl");
			rem = PayInterface.insertWeChatPay(map, request);
		} else {// 支付宝
			map.put("url", url + "/shuiweilai/api/alipayCallbackUrl");
			rem = PayInterface.insertAlipayPay(map);
		}
		return rem;
	}

	// 支付宝回调
	public Map<String, Object> alipayCallbackUrl(HttpServletRequest request) throws Exception {
		Map<String, Object> rem = PayInterface.alipayNotifyUrl(request);
		if ("0".equals(String.valueOf(rem.get("code")))) {
			dao.updateOrderStatus(rem);
		}
		return rem;
	}

	// 微信回调
	public void WxcallbackUrl(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> rem = PayInterface.wxTradePagePayNotifyUrl(request, response);
		if ("0".equals(String.valueOf(rem.get("code")))) {
			dao.updateOrderStatus(rem);
		}
	}

	public List<Map<String, Object>> getOrderList(Map<String, Object> map) {
		if (map.containsKey("orderStatus") && "0".equals(String.valueOf(map.get("orderStatus")))) {
			map.put("orderStatus", "0");
		}
		List<Map<String, Object>> list = dao.getOrderList(map);
		for (Map<String, Object> m : list) {
			m.put("goodsList", dao.getOrderGoods(m));
		}
		return list;
	}

	public Map<String, Object> payOrder(Map<String, Object> map, HttpServletRequest request) throws Exception {
		Map<String, Object> rem = new HashMap<>();
		Map<String, Object> order = dao.getOrderPrice(map);
		int payType = Integer.parseInt(String.valueOf(map.get("payType")));
		BigDecimal totalPrice = new BigDecimal(String.valueOf(order.get("actualPrice")));
		if (payType == 1) {// 微信
			map.put("url", url + "/shuiweilai/api/pWxcallbackUrl");
			map.put("price", totalPrice);
			rem = PayInterface.insertWeChatPay(map, request);
		} else {// 支付宝
			map.put("url", url + "/shuiweilai/api/palipayCallbackUrl");
			map.put("price", totalPrice);
			rem = PayInterface.insertAlipayPay(map);
		}
		return rem;
	}

	// 支付宝回调
	public Map<String, Object> palipayCallbackUrl(HttpServletRequest request) throws Exception {
		Map<String, Object> rem = PayInterface.alipayNotifyUrl(request);
		if ("0".equals(String.valueOf(rem.get("code")))) {
			dao.updateOrderStatusSubOrder(rem);
		}
		return rem;
	}

	// 微信回调
	public void pWxcallbackUrl(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> rem = PayInterface.wxTradePagePayNotifyUrl(request, response);
		if ("0".equals(String.valueOf(rem.get("code")))) {
			dao.updateOrderStatusSubOrder(rem);
		}
	}

	public int updateOrderStatusBySub(Map<String, Object> map) {
		map.put("orderStatus", 3);
		return dao.updateOrderStatusBySub(map);
	}

	@Transactional
	public int deleteOrder(Map<String, Object> map) {
		dao.deleteOrderDetail(map);
		return dao.deleteOrder(map);
	}

	public int returnOrder(Map<String, Object> map) {
		map.put("orderStatus", 4);
		return dao.updateOrderStatusBySub(map);
	}

	public Map<String, Object> returnPrice(Map<String, Object> param) throws Exception {
		Map<String, Object> rem = new HashMap<>();
		Map<String, Object> map = dao.getOrderPrice(param);
		if (map != null) {
			String payType = String.valueOf(map.get("payType"));
			String orderStatus = String.valueOf(map.get("orderStatus"));
			if ("4".equals(orderStatus)) {
				if ("1".equals(payType)) {
					int i = PayInterface.wxRefund(String.valueOf(map.get("subOrder")),
							String.valueOf(map.get("actualPrice")), String.valueOf(map.get("actualPrice")));
					if (i == 0) {
						param.put("orderStatus", 5);
						dao.updateOrderStatusBySub(param);
						rem.put("code", 0);
						rem.put("msg", "退款成功");

					} else {
						rem.put("code", 1);
						rem.put("msg", "退款失败");
					}
				} else {
					int i = PayInterface.alipayRefund(String.valueOf(map.get("subOrder")),
							String.valueOf(map.get("actualPrice")));
					if (i == 0) {
						param.put("orderStatus", 5);
						dao.updateOrderStatusBySub(param);
						rem.put("code", 0);
						rem.put("msg", "退款成功");

					} else {
						rem.put("code", 1);
						rem.put("msg", "退款失败");
					}
				}
			} else {
				rem.put("code", 1);
				rem.put("msg", "订单异常");
			}
		} else {
			rem.put("code", 1);
			rem.put("msg", "订单不存在");
		}
		return rem;
	}

	// 未领取优惠卷列表
	public List<Coupon> getShopCoupon(Map<String, Object> map) {
		map.put("shopIds", "1," + map.get("shopId"));
		return dao.getShopCoupon(map);
	}

	// 领取优惠卷
	public Map<String, Object> insertMemberCoupon(Map<String, Object> param) {
		Map<String, Object> map = new HashMap<>();
		List<Coupon> list = dao.getShopCoupon(param);
		if (list.size() > 0) {
			Coupon coupon = list.get(0);
			coupon.setMemberId(Long.parseLong(String.valueOf(param.get("memberId"))));
			dao.insertMemberCoupon(coupon);
			map.put("code", 0);
			map.put("msg", "领取成功");
		} else {
			map.put("code", 1);
			map.put("msg", "优惠卷不存在");
		}
		return map;
	}

	// 优惠卷列表
	public List<Coupon> getMemberCouponNum(Map<String, Object> map) {
		return dao.getMemberCouponNum(map);
	}

	// 会员商品收藏
	@Transactional
	public void updateCollect(Map<String, Object> map) {
		if (dao.getCollect(map) == 0) {
			dao.insertCollect(map);
		} else {
			dao.deleteCollect(map);
		}
	}

	// 会员商品浏览记录
	@Transactional
	public void insertBrowsing(Map<String, Object> map) {
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		map.put("browsingTime",sdf.format(new Date()));
		if(dao.getBrowsing(map)==0){
			dao.insertBrowsing(map);
		}

	}

}
